<template>
	<view class="payment">
		<view class="bg-color" style="width:100%;height:30rpx"></view>
		<!-- 收货地址 -->
		<view v-if="order.addressMsg.address" class="address flex-row border-radius-sm"
			style="background-color: #fff;width:100%;height:150rpx">
			<view class="flex-row-ct theme-color margin-lr-com iconfont icon-dingwei1" style="font-size: 25px"></view>
			<view class="flex-column-st">
				<view class="message" type="text">{{order.addressMsg.address}}</view>
				<view class="name" type="text">{{order.addressMsg.receiver}} {{order.addressMsg.phone}}</view>
			</view>
			<view class="flex-row-ct" style="margin-left: auto;">
				<view class="flex-row-ct theme-color iconfont icon-you" style="font-size: 20px;margin-left: auto;"
					@click="toAddress"></view>
			</view>
		</view>
		<view v-else class="address border-radius-sm text-bold theme-color" @click="toAddress"
			style="background-color: #fff;width:100%;height:150rpx;text-align: center;line-height: 150rpx;">
			没有地址信息,请点击后添加地址
		</view>
		<!-- 购买商品列表 -->
		<view class="margin-tb-com border-radius-sm" style="background-color: #fff;width: 100%;height: fit-content">
			<view class="padding-sm" v-for="(item,index) in order.order_list" :key="index">
				<view class="flex-row">
					<!-- 商品图片 -->
					<image :src="imgURL+item.indexImg" mode="aspectFill" class="border-radius-sm margin-right-sm"
						style="width: 180rpx;height: 180rpx;"></image>
					<!-- 内容 -->
					<view class="" style="height: 100%;width: 100%;position: relative;">
						<view class="flex-row-bt text-lg text-bold">
							<view>{{item.productName}}</view>
							<view class="theme-color">￥{{item.monovalent}}</view>
						</view>
						<view style="position: absolute;top: 130rpx;right: 0;">
							<uv-number-box v-model="item.num" :max="item.inventory" :min="1">
								<template v-slot:minus>
									<view class="minus">
										<uv-icon name="minus" size="14">
										</uv-icon>
									</view>
								</template>
								<template v-slot:input>
									<text style="width: 40rpx;text-align: center;" class="input">
										{{item.num}}
									</text>
								</template>
								<template v-slot:plus>
									<view class="plus">
										<uv-icon name="plus" size="14">
										</uv-icon>
									</view>
								</template>
							</uv-number-box>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 支付方式 -->
		<view class="border-radius-sm" style="background-color: #fff;height:130rpx;width:100%">
			<view class="flex-row-st" style="width:100%;height:100%">
				<view class="margin-left-com" style="font-size: 30rpx;">支付方式</view>
				<view class="margin-right-com iconfont icon-weixin"
					style="margin-left: auto;font-size: 30px;color:#28c445"></view>
				<text class="margin-right-com" style="font-size: 30rpx;">微信支付</text>
			</view>
		</view>
		<!-- 底部导航栏 -->
		<view class="bg-color" style="width:100%;height:130rpx"></view>
		<view class="tabbar flex-row-ct padding-left-com" style="position: fixed;left: 0; right: 0;width:100%;height:60px;
		background-color: #fff;" :style="{bottom:bottomSafeArea+'px'}">
			<text style="font-size: 14px;">共{{numselected}}件，</text>
			<text style="font-size: 14px;">合计:</text>
			<view class="account theme-color" style="font-size: 16px;">￥{{totalPrice}}</view>
			<view class="nav" style="margin-left: auto">
				<button class=" theme-bg-color margin-right-com" type="default" size="mini"
					style="color:#fff;border-radius: 30rpx;" @click="payOrder()">提交订单</button>

			</view>
		</view>
	</view>
	<!-- 接口请求加载动画 -->
	<loading></loading>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	import {
		imgURL
	} from '../../api/request';
	import {
		onLoad, onShow
	} from '@dcloudio/uni-app'
	import { OrderType, ToPayData, toCreateOrder } from '../../api/wxpay/wxpay';
	import { deliveryAddress } from '../../api/shop/shop';
	import store from '../../store/login';

	// 底部安全距离
	const bottomSafeArea = uni.getStorageSync('bottomSafeArea')
	//是否选中
	const selected = ref(false)

	//test
	const selectCartList = ref([])

	//商品数量
	const numselected = computed(() => {
		if (order.order_list.length !== 0) {
			let a = 0
			order.order_list.forEach(item => {
				a = a + item.num
			})
			return a
		} else {
			return 0
		}
		// return products.order_list.reduce((sum, item) => {
		// 	return sum + item.num
		// }, 0)
	})

	const order = reactive({
		outTradeNo: null,
		timeStamp: null,
		total: null,
		order_list: [{
			id: "1780640338535264256",
			indexImg: "/profile/product/2024/05/10/下载 (1)_20240510163143A011.jpg",
			inventory: 20,
			monovalent: "31.00",
			num: 1,
			productName: "初动果肉果冻",
		}],
		addressMsg: {
			// "pkId": "1796429051964547074",
			// "userId": "1793129894038286337",
			// "address": "萍乡学院",
			// "receiver": "曾月星",
			// "phone": "18297898672",
			// "defaultFlag": null
		}
	})

	onLoad(() => {
		order.order_list = uni.getStorageSync('orders')
		console.log('order', order.order_list)
		if (uni.getStorageSync('openId')) {
		} else {
			store.loginTip()
		}
	})

	onShow(() => {
		getAddress()
	})

	//计算总价
	const totalPrice = computed(() => {
		if (order.order_list.length !== 0) {
			console.log(order.order_list)
			let total = 0
			order.order_list.forEach(item => {
				total = total + item.num * Number(item.monovalent)
			})
			return total
		} else {
			return 0.00
		}
	})

	const toAddress = () => {
		uni.navigateTo({
			url: '/pages/shop/address'
		});
	}

	//获取用户收获地址
	const getAddress = () => {
		console.log(uni.getStorageSync('address'))
		if (uni.getStorageSync('address')) {
			order.addressMsg = JSON.parse(uni.getStorageSync('address'))
		} else {
			deliveryAddress().then(res => {
				order.addressMsg = res.data[0]
				for (let i = 0; i < res.data.length; i++) {
					if (res.data.defaultFlag == 1) {
						order.addressMsg = res.data[i]
					}
				}
			})
		}
	}

	//支付
	const payOrder = () => {
		var payData : OrderType = {
			// total: 1,
			total: totalPrice.value * 100,
			description: "商品支付",
			openId: uni.getStorageSync('openId'),
			// outTradeNo: ''
		};
		order.total = totalPrice.value
		wxpay(payData);
	}

	const wxpay = (data : OrderType) => {
		console.log('订单' + JSON.stringify(order))
		toCreateOrder(data).then((res : ToPayData) => {
			if (res.code == 200) {
				console.log(JSON.stringify(res))
				//订单对象，从服务器获取 测试支付
				var orderInfoData = {
					timeStamp: res.data.timeStamp, // 时间戳
					nonceStr: res.data.nonceStr, // 随机字符串
					wxPackage: res.data.wxPackage, // 统一下单接口返回的 prepay_id 参数值
					signType: res.data.signType, // 签名方式
					paySign: res.data.paySign, // 签名
					outTradeNo: res.data.outTradeNo
				};
				order.outTradeNo = res.data.outTradeNo
				order.timeStamp = res.data.timeStamp
				console.log(orderInfoData);
				uni.getProvider({
					service: 'payment',
					success: function (res) {
						console.log(res.provider)
						if (~res.provider.indexOf('wxpay')) {
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: "",
								timeStamp: orderInfoData.timeStamp,
								nonceStr: orderInfoData.nonceStr,
								package: orderInfoData.wxPackage,
								paySign: orderInfoData.paySign,
								signType: orderInfoData.signType,
								success: function (res) {
									console.log(res);
									uni.showToast({
										//后台把错误请求信息放在msg中 
										title: "支付成功",
										icon: "none"
									});
									// uni.setStorageSync('orders', [])
									uni.redirectTo({
										url: '/pages/supermarket/order_detail?order=' + JSON.stringify(order)
									})
								},
								fail: function (err) {
									//关单
									console.log(err);
									console.log("微信开始关单啦");
									// toCloseOrder(orderInfoData.outTradeNo);
								}
							});
						}
					}
				});
			} else {
				uni.showToast({
					//后台把错误请求信息放在msg中 
					title: res.msg,
					icon: "none"
				});
			}
		})
	}
</script>

<style lang="scss" scoped>
	.payment {
		background-color: #efefef;
		height: 100vh;



		.tabbar {
			box-shadow: $uni-shadow-lg;
		}
	}

	::-webkit-scrollbar {
		//隐藏或取消滚动条
		display: none;
	}

	.minus {
		width: 24px;
		height: 24px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.input {
		padding: 0 10px;
	}

	.plus {
		width: 24px;
		height: 24px;
		background-color: #FF0000;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	::-webkit-scrollbar {
		display: none;
		width: 0;
		height: 0;
		color: transparent;
	}
</style>